const { query } = require('./db');

function getUserByEmail(email, callback) {
    console.log(email)
    query('SELECT * FROM users WHERE email =?', [email], (error, results, fields) => {
        if (error) {
            return callback(error);
        }
        console.log(results)
        if (results.length === 0) {
            return callback(null, null);
        }
        return callback(null, results[0]);
    });
}

function addUser(user, callback) {
    query('insert into users set ? ', user, (err, results) => {
        if (err) {
            return callback(err)
        }
        console.log('add user', results)
        callback(err, results)
    })
}

function login(email, password, callback) {
    getUserByEmail(email, (error, user) => {
        if (error) {
            return callback(error);
        }
        if (!user) {
            return callback(null, null, 'user not exist');
        }
        if (user.password !== password) {
            return callback(null, null, 'password error');
        }
        return callback(null, user);
    });
}


function register(user, callback) {
    getUserByEmail(user.email, (err, results) => {
        if (err) {
            return callback(err)
        }
        if (results) {
            return callback(null, null, 'user exist !!');
        } else {

            addUser(user, (err, results) => {
                if (err) {
                    return callback(err)
                }
                callback(null, user)
            })
        }

    })

}

//  {"username":"test", "email":"lisi@qq.com","password":"123456"}

module.exports = {
    login, register
};